package com.example.demo2.test.websocket;

import com.example.demo2.test.factory.ConnectionFactory;
import com.example.demo2.test.pong.OkPong;
import com.example.demo2.test.service.OkService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 火币websocket连接管理类
 * @author yusong
 * @date 
 */
@Data
@Slf4j
public class OkWebSocket extends WebSocketListener{

//	private String uri = "wss://ws.okex.com:8443/ws/v5/public";
//	private String uri = "wss://wspri.coinall.ltd:8443/ws/v5/public";

	private OkService okService;
	//websocket连接
	private WebSocket webSocket;
	//定义一个request信息
	private Request okhttpRequest;
	//定义一个私有的构造函数 防止外部创建
	private OkWebSocket() {}
	/**
	 * 创建websocket连接
	 * @return
	 */
	public static OkWebSocket createConnectionManage(OkService okService, String uri) {
		OkWebSocket okWebSocket = new OkWebSocket();
		okWebSocket.setOkService(okService);
		Request request = new Request.Builder().url(uri).build();
		okWebSocket.setOkhttpRequest(request);
		okWebSocket.connect();
		return okWebSocket;
	}
	
	//开启一个1个线程的连接池 用于检测连接是否正常
	static ExecutorService pool = Executors.newFixedThreadPool(1);
	static OkPong pong = null;
	/**
	 * 提供一个非静态的方法 创建webSocket
	 */
	private void connect() {
		webSocket = ConnectionFactory.createWebSocket(okhttpRequest, this);
		pong = new OkPong(webSocket);
		pool.submit(pong);
		
	}
	
	/**
	 * 从ok订阅消息
	 * @param subscribeStr	订阅的消息
	 */
	public void send(String subscribeStr) {
		this.webSocket.send(subscribeStr);
	}
	
	
	
	// 建立socket连接的时候调用
	public void onOpen(WebSocket webSocket, Response response) {}

	// 收到传递String类型参数时调用
	public void onMessage(WebSocket webSocket, String text) {
		//处理ping pong的包
		if("pong".equals(text)) {
			return;
		}
		//处理对应的业务
		if(text.contains("data")){
			okService.message(text);
		}
	}

	// 接收ByteString类型数据的时候调用
	public void onMessage(WebSocket webSocket, ByteString bytes) {
	}

	// 连接关闭的时候调用
	public void onClosing(WebSocket webSocket, int code, String reason) {
		log.info("onClosed");
	}

	// 连接关闭后调用
	public void onClosed(WebSocket webSocket, int code, String reason) {
		log.info("onClosed");
	}

	// 连接失败调用
	public void onFailure(WebSocket webSocket, Throwable t, Response response) {
	log.info("onFailure");
	}

}
